<template>
  <view class="checkin-container">
    <!-- 今日签到状态 -->
    <view class="today-checkin-section">
      <view class="checkin-card card">
        <view class="checkin-header">
          <text class="checkin-date">{{ todayDate }}</text>
          <text class="checkin-day">戒烟第 {{ quitDays }} 天</text>
        </view>
        
        <view class="checkin-status" v-if="!todayCheckedIn">
          <view class="status-icon">⏰</view>
          <text class="status-text">今日还未签到</text>
          <button class="btn btn-primary checkin-btn" @click="doCheckin">
            立即签到
          </button>
        </view>
        
        <view class="checkin-status checked" v-else>
          <view class="status-icon">✅</view>
          <text class="status-text">今日已签到</text>
          <text class="checkin-time">签到时间：{{ todayCheckinTime }}</text>
        </view>
        
        <view class="mood-section" v-if="todayCheckedIn">
          <text class="mood-title">今日心情</text>
          <view class="mood-selector">
            <view class="mood-item" 
                  v-for="(mood, index) in moods" 
                  :key="index"
                  :class="{ active: selectedMood === index }"
                  @click="selectMood(index)">
              <text class="mood-emoji">{{ mood.emoji }}</text>
              <text class="mood-text">{{ mood.text }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 签到统计 -->
    <view class="stats-section">
      <view class="section-title">
        <text>签到统计</text>
      </view>
      <view class="stats-cards">
        <view class="stat-card card">
          <view class="stat-icon">🏆</view>
          <view class="stat-content">
            <text class="stat-value">{{ totalCheckins }}</text>
            <text class="stat-label">总签到天数</text>
          </view>
        </view>
        <view class="stat-card card">
          <view class="stat-icon">🔥</view>
          <view class="stat-content">
            <text class="stat-value">{{ continuousCheckins }}</text>
            <text class="stat-label">连续签到</text>
          </view>
        </view>
        <view class="stat-card card">
          <view class="stat-icon">📈</view>
          <view class="stat-content">
            <text class="stat-value">{{ checkinRate }}%</text>
            <text class="stat-label">签到率</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 签到日历 -->
    <view class="calendar-section">
      <view class="section-title">
        <text>签到日历</text>
      </view>
      <view class="calendar-card card">
        <view class="calendar-header">
          <button class="calendar-nav" @click="previousMonth">‹</button>
          <text class="calendar-title">{{ currentMonthTitle }}</text>
          <button class="calendar-nav" @click="nextMonth">›</button>
        </view>
        
        <view class="calendar-weekdays">
          <text class="weekday" v-for="day in weekdays" :key="day">{{ day }}</text>
        </view>
        
        <view class="calendar-days">
          <view class="calendar-day" 
                v-for="(day, index) in calendarDays" 
                :key="index"
                :class="{ 
                  'other-month': day.otherMonth,
                  'checked-in': day.checkedIn,
                  'today': day.isToday,
                  'future': day.isFuture
                }">
            <text class="day-number">{{ day.day }}</text>
            <view class="day-status" v-if="day.checkedIn && !day.otherMonth">
              <text class="status-dot">•</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 签到奖励 -->
    <view class="rewards-section">
      <view class="section-title">
        <text>签到奖励</text>
      </view>
      <view class="rewards-card card">
        <view class="reward-item" 
              v-for="(reward, index) in rewards" 
              :key="index"
              :class="{ achieved: reward.achieved, available: reward.available }">
          <view class="reward-icon">{{ reward.icon }}</view>
          <view class="reward-content">
            <text class="reward-title">{{ reward.title }}</text>
            <text class="reward-desc">{{ reward.desc }}</text>
          </view>
          <view class="reward-status">
            <text class="status-text" v-if="reward.achieved">已获得</text>
            <text class="status-text available" v-else-if="reward.available">可领取</text>
            <text class="status-text">{{ reward.progress }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { CheckinData } from '../../types/global.d.ts'
import { useSmokingHistoryStore } from '@/store/smokingHistory'
import { storeToRefs } from 'pinia'

// 响应式数据
const checkinData = ref<CheckinData>({})
const selectedMood = ref<number>(-1)
const currentMonth = ref<number>(new Date().getMonth())
const currentYear = ref<number>(new Date().getFullYear())

const { quitDate } = storeToRefs(useSmokingHistoryStore())

// 常量
const weekdays = ['日', '一', '二', '三', '四', '五', '六']
const moods = [
  { emoji: '😊', text: '很好' },
  { emoji: '😐', text: '一般' },
  { emoji: '😔', text: '不好' },
  { emoji: '💪', text: '坚强' },
  { emoji: '🎉', text: '开心' }
]

// 计算属性
const todayDate = computed((): string => {
  const today = new Date()
  return `${today.getFullYear()}年${today.getMonth() + 1}月${today.getDate()}日`
})

const quitDays = computed(() => {
  if (!quitDate.value) return 0
  const quit = new Date(quitDate.value)
  const now = new Date()
  const diffTime = Math.abs(now.getTime() - quit.getTime())
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
})

const todayCheckedIn = computed(() => {
  const today = new Date().toDateString()
  return !!checkinData.value[today]
})

const todayCheckinTime = computed(() => {
  const today = new Date().toDateString()
  const checkinInfo = checkinData.value[today]
  if (checkinInfo && checkinInfo.time) {
    return new Date(checkinInfo.time).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  return ''
})

const totalCheckins = computed(() => {
  return Object.keys(checkinData.value).length
})

const continuousCheckins = computed(() => {
  if (Object.keys(checkinData.value).length === 0) return 0
  
  let count = 0
  const today = new Date()
  
  for (let i = 0; i < quitDays.value; i++) {
    const checkDate = new Date(today.getTime() - i * 24 * 60 * 60 * 1000)
    const dateKey = checkDate.toDateString()
    
    if (checkinData.value[dateKey]) {
      count++
    } else {
      break
    }
  }
  
  return count
})

const checkinRate = computed(() => {
  if (quitDays.value === 0) return 0
  return Math.round((totalCheckins.value / quitDays.value) * 100)
})

const currentMonthTitle = computed(() => {
  return `${currentYear.value}年${currentMonth.value + 1}月`
})

const calendarDays = computed(() => {
  const year = currentYear.value
  const month = currentMonth.value
  
  // 获取当月第一天是星期几
  const firstDay = new Date(year, month, 1).getDay()
  // 获取当月总天数
  const daysInMonth = new Date(year, month + 1, 0).getDate()
  // 获取上月总天数
  const daysInPrevMonth = new Date(year, month, 0).getDate()
  
  const days = []
  const today = new Date()
  
  // 添加上月末尾几天
  for (let i = firstDay - 1; i >= 0; i--) {
    days.push({
      day: daysInPrevMonth - i,
      otherMonth: true,
      checkedIn: false,
      isToday: false,
      isFuture: false
    })
  }
  
  // 添加当月所有天
  for (let day = 1; day <= daysInMonth; day++) {
    const currentDate = new Date(year, month, day)
    const dateKey = currentDate.toDateString()
    const isToday = currentDate.toDateString() === today.toDateString()
    const isFuture = currentDate > today
    
    days.push({
      day,
      otherMonth: false,
      checkedIn: !!checkinData.value[dateKey],
      isToday,
      isFuture
    })
  }
  
  // 补齐下月开头几天
  const remainingDays = 42 - days.length
  for (let day = 1; day <= remainingDays; day++) {
    days.push({
      day,
      otherMonth: true,
      checkedIn: false,
      isToday: false,
      isFuture: false
    })
  }
  
  return days
})

const rewards = computed(() => {
  const continuous = continuousCheckins.value
  const total = totalCheckins.value
  
  return [
    {
      icon: '🌟',
      title: '初来乍到',
      desc: '完成首次签到',
      achieved: total >= 1,
      available: total >= 1,
      progress: `${Math.min(total, 1)}/1`
    },
    {
      icon: '🏅',
      title: '坚持不懈',
      desc: '连续签到7天',
      achieved: continuous >= 7,
      available: continuous >= 7,
      progress: `${Math.min(continuous, 7)}/7`
    },
    {
      icon: '💎',
      title: '钻石意志',
      desc: '连续签到30天',
      achieved: continuous >= 30,
      available: continuous >= 30,
      progress: `${Math.min(continuous, 30)}/30`
    },
    {
      icon: '👑',
      title: '签到之王',
      desc: '累计签到100天',
      achieved: total >= 100,
      available: total >= 100,
      progress: `${Math.min(total, 100)}/100`
    }
  ]
})

// 页面加载
onMounted(() => {
  loadData()
})

// 方法
const loadData = () => {
  checkinData.value = uni.getStorageSync('checkinData') || {}
  // 加载今日心情
  const today = new Date().toDateString()
  const todayData = checkinData.value[today]
  if (todayData && todayData.mood !== undefined) {
    selectedMood.value = todayData.mood
  }
}

const doCheckin = () => {
  const today = new Date().toDateString()
  const now = new Date()
  
  checkinData.value[today] = {
    time: now.toISOString(),
    mood: -1
  }
  
  uni.setStorageSync('checkinData', checkinData.value)
  
  uni.showToast({
    title: '签到成功！',
    icon: 'success'
  })
  
  // 检查奖励
  checkRewards()
}

const selectMood = (moodIndex: number) => {
  selectedMood.value = moodIndex
  
  const today = new Date().toDateString()
  if (checkinData.value[today]) {
    checkinData.value[today].mood = moodIndex
    uni.setStorageSync('checkinData', checkinData.value)
    
    uni.showToast({
      title: '心情已记录',
      icon: 'success'
    })
  }
}

const previousMonth = () => {
  if (currentMonth.value === 0) {
    currentMonth.value = 11
    currentYear.value--
  } else {
    currentMonth.value--
  }
}

const nextMonth = () => {
  if (currentMonth.value === 11) {
    currentMonth.value = 0
    currentYear.value++
  } else {
    currentMonth.value++
  }
}

const checkRewards = () => {
  const newRewards = rewards.value.filter(reward => 
    reward.available && !reward.achieved
  )
  
  if (newRewards.length > 0) {
    uni.showModal({
      title: '恭喜获得奖励！',
      content: `获得了"${newRewards[0].title}"奖励！`,
      showCancel: false
    })
  }
}
</script>

<style lang="scss" scoped>
.checkin-container {
  padding: 20rpx;
}

.checkin-card {
  .checkin-header {
    text-align: center;
    margin-bottom: 30rpx;
    
    .checkin-date {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      margin-bottom: 10rpx;
    }
    
    .checkin-day {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .checkin-status {
    text-align: center;
    
    .status-icon {
      font-size: 80rpx;
      margin-bottom: 20rpx;
    }
    
    .status-text {
      display: block;
      font-size: 28rpx;
      margin-bottom: 30rpx;
    }
    
    .checkin-btn {
      width: 200rpx;
      height: 80rpx;
    }
    
    .checkin-time {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-top: 10rpx;
    }
    
    &.checked {
      .status-text {
        color: #4facfe;
        font-weight: 500;
      }
    }
  }
  
  .mood-section {
    margin-top: 40rpx;
    padding-top: 30rpx;
    border-top: 1rpx solid #f0f0f0;
    
    .mood-title {
      display: block;
      font-size: 26rpx;
      margin-bottom: 20rpx;
      text-align: center;
    }
    
    .mood-selector {
      display: flex;
      justify-content: space-around;
      
      .mood-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20rpx;
        border-radius: 12rpx;
        transition: all 0.3s ease;
        
        &.active {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #fff;
        }
        
        .mood-emoji {
          font-size: 40rpx;
          margin-bottom: 8rpx;
        }
        
        .mood-text {
          font-size: 22rpx;
        }
      }
    }
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  color: #333;
}

.stats-cards {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
  
  .stat-card {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 30rpx 20rpx;
    
    .stat-icon {
      font-size: 40rpx;
      margin-right: 15rpx;
    }
    
    .stat-content {
      .stat-value {
        display: block;
        font-size: 28rpx;
        font-weight: 600;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 22rpx;
        color: #666;
      }
    }
  }
}

.calendar-card {
  .calendar-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30rpx;
    
    .calendar-nav {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background: #f8f9fa;
      border: none;
      font-size: 54rpx;
      line-height: 54rpx;
      color: #667eea;
      &::after {
        border: none;
      }
    }
    
    .calendar-title {
      width: 156rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: 600;
    }
  }
  
  .calendar-weekdays {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 10rpx;
    margin-bottom: 20rpx;
    
    .weekday {
      text-align: center;
      font-size: 24rpx;
      color: #666;
      padding: 10rpx 0;
    }
  }
  
  .calendar-days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 10rpx;
    
    .calendar-day {
      position: relative;
      aspect-ratio: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 12rpx;
      
      &.other-month {
        color: #ccc;
      }
      
      &.today {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
      }
      
      &.checked-in:not(.today) {
        background: #4facfe;
        color: #fff;
      }
      
      &.future {
        color: #ddd;
      }
      
      .day-number {
        font-size: 24rpx;
      }
      
      .day-status {
        position: absolute;
        bottom: 4rpx;
        
        .status-dot {
          font-size: 20rpx;
          color: #fff;
        }
      }
    }
  }
}

.rewards-card {
  .reward-item {
    display: flex;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.achieved {
      opacity: 0.7;
    }
    
    &.available {
      background: linear-gradient(90deg, rgba(79, 172, 254, 0.1) 0%, rgba(0, 242, 254, 0.1) 100%);
      border-radius: 12rpx;
      margin: 0 -20rpx;
      padding: 25rpx 20rpx;
    }
    
    .reward-icon {
      font-size: 40rpx;
      margin-right: 20rpx;
    }
    
    .reward-content {
      flex: 1;
      
      .reward-title {
        display: block;
        font-size: 28rpx;
        font-weight: 500;
        margin-bottom: 8rpx;
      }
      
      .reward-desc {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .reward-status {
      .status-text {
        font-size: 22rpx;
        color: #666;
        
        &.available {
          color: #4facfe;
          font-weight: 500;
        }
      }
    }
  }
}

.reminder-card {
  .reminder-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .reminder-label {
      font-size: 28rpx;
    }
    
    .time-picker {
      padding: 10rpx 20rpx;
      background: #f8f9fa;
      border-radius: 8rpx;
      font-size: 26rpx;
      color: #667eea;
    }
  }
}
</style>